All files / model field_value.ts

99.09% Statements 327/330
96.03% Branches 145/151
98.82% Functions 84/85
99% Lines 297/300
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678                                          2x 2x 2x   2x                                             2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x       2x 2x 2x 2x       2x 2x       18x   2x 419x   4x   12x     403x         2x                                   2x             2x 3564x 3564x     2x 7979x       7979x 7979x   2x   2x 2x       2x     2x     2x 191x     2x 97x     2x 150x 3x   147x     2x 2x   2x 4x   4x 4x     2x 807x     2x 345x           2x 334x 46x   288x     2x 311x     2x 2x 2x     2x 6081x   6081x 6081x     2x 4018x     2x 48096x 46177x   1919x   2x       46177x 20131x 26046x 21976x 4070x 3994x     76x 40x   36x                       1364x   999x     365x       2x         2x     1333x 1021x   312x         2x   2x 3412x 3412x     2x 2x 2x   2x     584x 343x   241x         2x     2x 3449x   3449x 3449x     2x 3697x     2x 1333x         2x 1272x 264x   1008x   2x   2x 144x   144x 144x     2x 345x     2x 203x           2x 284x 20x 264x   8x   256x     2x                               2x 68x     68x 68x   68x     2x 44x       6x 38x       16x   22x       2x 167x           2x 272x 8x 264x   8x   256x       2x 270x   2x   2x 19x   19x 19x     2x 278x     2x 136x           2x 680x 50x   630x   2x   2x 142x   142x 142x     2x 432x     2x 422x 272x       150x       2x 850x 93x 93x   757x   2x   2x 27x   27x 27x     2x 286x     2x 136x           2x 1632x 288x   1344x   2x   2x 10220x   10220x 10220x     2x 1303x 1303x 1708x   1303x     2x 2968x     2x 2059x 1853x 1853x 1853x 2016x 2016x 2016x 381x       1472x     206x     2x 683x 53x 53x 53x 63x 63x   63x   63x 37x         16x   630x       2x 4310x 4310x 4225x   85x 85x 33x   85x 85x       2x 38x       38x 21x     17x 17x 13x 13x         4x         2x       2x 95066x 95066x 95066x 95238x 95214x   24x     95066x     2x 538x     2x 102x     2x 4310x     2x     2x   2x 82x   82x 82x     2x 723x     2x 30x     2x 190x 20x 10x     10x 19x         10x     170x     2x 819x 75x         75x 75x   75x 29x       46x         744x       2x 360x   2x  
/**
 * Copyright 2017 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
import { Blob } from '../api/blob';
import { GeoPoint } from '../api/geo_point';
import { SnapshotOptions } from '../api/database';
import { DatabaseId } from '../core/database_info';
import { Timestamp } from '../core/timestamp';
import { assert, fail } from '../util/assert';
import { primitiveComparator } from '../util/misc';
import { SortedMap } from '../util/sorted_map';
 
import { DocumentKey } from './document_key';
import { FieldPath } from './path';
 
/**
 * Supported data value types:
 *  - Null
 *  - Boolean
 *  - Long
 *  - Double
 *  - String
 *  - Object
 *  - Array
 *  - Binary
 *  - Timestamp
 *  - ServerTimestamp (a sentinel used in uncommitted writes)
 *  - GeoPoint
 *  - (Document) References
 */
 
export interface JsonObject<T> {
  [name: string]: T;
}
 
export enum TypeOrder {
  // This order is defined by the backend.
  NullValue = 0,
  BooleanValue = 1,
  NumberValue = 2,
  TimestampValue = 3,
  StringValue = 4,
  BlobValue = 5,
  RefValue = 6,
  GeoPointValue = 7,
  ArrayValue = 8,
  ObjectValue = 9
}
 
/** Defines the return value for pending server timestamps. */
export enum ServerTimestampBehavior {
  Default,
  Estimate,
  Previous
}
 
/** Holds properties that define field value deserialization options. */
export class FieldValueOptions {
  static readonly defaultOptions = new FieldValueOptions(
    ServerTimestampBehavior.Default
  );
 
  constructor(readonly serverTimestampBehavior: ServerTimestampBehavior) {}
 
  static fromSnapshotOptions(options: SnapshotOptions) {
    switch (options.serverTimestamps) {
      case 'estimate':
        return new FieldValueOptions(ServerTimestampBehavior.Estimate);
      case 'previous':
        return new FieldValueOptions(ServerTimestampBehavior.Previous);
      case 'none': // Fall-through intended.
      case undefined:
        return FieldValueOptions.defaultOptions;
      default:
        return fail('fromSnapshotOptions() called with invalid options.');
    }
  }
}
 
/**
 * Potential types returned by FieldValue.value(). This could be stricter
 * (instead of using {}), but there's little benefit.
 *
 * Note that currently we use AnyJs (which is identical except includes
 * undefined) for incoming user data as a convenience to the calling code (but
 * we'll throw if the data contains undefined). This should probably be changed
 * to use FieldType, but all consuming code will have to be updated to
 * explicitly handle undefined and then cast to FieldType or similar. Perhaps
 * we should tackle this when adding robust argument validation to the API.
 */
export type FieldType = null | boolean | number | string | {};
 
/**
 * A field value represents a datatype as stored by Firestore.
 */
export abstract class FieldValue {
  readonly typeOrder: TypeOrder;
 
  abstract value(options?: FieldValueOptions): FieldType;
  abstract isEqual(other: FieldValue): boolean;
  abstract compareTo(other: FieldValue): number;
 
  toString(): string {
    const val = this.value();
    return val === null ? 'null' : val.toString();
  }
 
  defaultCompareTo(other: FieldValue): number {
    assert(
      this.typeOrder !== other.typeOrder,
      'Default compareTo should not be used for values of same type.'
    );
    const cmp = primitiveComparator(this.typeOrder, other.typeOrder);
    return cmp;
  }
}
 
export class NullValue extends FieldValue {
  typeOrder = TypeOrder.NullValue;
 
  // internalValue is unused but we add it to work around
  // https://github.com/Microsoft/TypeScript/issues/15585
  readonly internalValue = null;
 
  private constructor() {
    super();
  }
 
  value(options?: FieldValueOptions): null {
    return null;
  }
 
  isEqual(other: FieldValue): boolean {
    return other instanceof NullValue;
  }
 
  compareTo(other: FieldValue): number {
    if (other instanceof NullValue) {
      return 0;
    }
    return this.defaultCompareTo(other);
  }
 
  static INSTANCE = new NullValue();
}
 
export class BooleanValue extends FieldValue {
  typeOrder = TypeOrder.BooleanValue;
 
  private constructor(readonly internalValue: boolean) {
    super();
  }
 
  value(options?: FieldValueOptions): boolean {
    return this.internalValue;
  }
 
  isEqual(other: FieldValue): boolean {
    return (
      other instanceof BooleanValue &&
      this.internalValue === other.internalValue
    );
  }
 
  compareTo(other: FieldValue): number {
    if (other instanceof BooleanValue) {
      return primitiveComparator(this, other);
    }
    return this.defaultCompareTo(other);
  }
 
  static of(value: boolean): BooleanValue {
    return value ? BooleanValue.TRUE : BooleanValue.FALSE;
  }
 
  static TRUE = new BooleanValue(true);
  static FALSE = new BooleanValue(false);
}
 
/** Base class for IntegerValue and DoubleValue. */
export abstract class NumberValue extends FieldValue {
  typeOrder = TypeOrder.NumberValue;
 
  constructor(readonly internalValue: number) {
    super();
  }
 
  value(options?: FieldValueOptions): number {
    return this.internalValue;
  }
 
  compareTo(other: FieldValue): number {
    if (other instanceof NumberValue) {
      return numericComparator(this.internalValue, other.internalValue);
    }
    return this.defaultCompareTo(other);
  }
}
 
/** Utility function to compare doubles (using Firestore semantics for NaN). */
function numericComparator(left: number, right: number): number {
  if (left < right) {
    return -1;
  } else if (left > right) {
    return 1;
  } else if (left === right) {
    return 0;
  } else {
    // one or both are NaN.
    if (isNaN(left)) {
      return isNaN(right) ? 0 : -1;
    } else {
      return 1;
    }
  }
}
 
/**
 * Utility function to check numbers for equality using Firestore semantics
 * (NaN === NaN, -0.0 !== 0.0).
 */
function numericEquals(left: number, right: number): boolean {
  // Implemented based on Object.is() polyfill from
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
  if (left === right) {
    // +0 != -0
    return left !== 0 || 1 / left === 1 / right;
  } else {
    // NaN == NaN
    return left !== left && right !== right;
  }
}
 
export class IntegerValue extends NumberValue {
  constructor(internalValue: number) {
    super(internalValue);
  }
 
  isEqual(other: FieldValue): boolean {
    // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,
    // but that doesn't make them equal via isEqual().
    if (other instanceof IntegerValue) {
      return numericEquals(this.internalValue, other.internalValue);
    } else {
      return false;
    }
  }
 
  // NOTE: compareTo() is implemented in NumberValue.
}
 
export class DoubleValue extends NumberValue {
  constructor(readonly internalValue: number) {
    super(internalValue);
  }
 
  static NAN = new DoubleValue(NaN);
  static POSITIVE_INFINITY = new DoubleValue(Infinity);
  static NEGATIVE_INFINITY = new DoubleValue(-Infinity);
 
  isEqual(other: FieldValue): boolean {
    // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,
    // but that doesn't make them equal via isEqual().
    if (other instanceof DoubleValue) {
      return numericEquals(this.internalValue, other.internalValue);
    } else {
      return false;
    }
  }
 
  // NOTE: compareTo() is implemented in NumberValue.
}
 
// TODO(b/37267885): Add truncation support
export class StringValue extends FieldValue {
  typeOrder = TypeOrder.StringValue;
 
  constructor(readonly internalValue: string) {
    super();
  }
 
  value(options?: FieldValueOptions): string {
    return this.internalValue;
  }
 
  isEqual(other: FieldValue): boolean {
    return (
      other instanceof StringValue && this.internalValue === other.internalValue
    );
  }
 
  compareTo(other: FieldValue): number {
    if (other instanceof StringValue) {
      return primitiveComparator(this.internalValue, other.internalValue);
    }
    return this.defaultCompareTo(other);
  }
}
 
export class TimestampValue extends FieldValue {
  typeOrder = TypeOrder.TimestampValue;
 
  constructor(readonly internalValue: Timestamp) {
    super();
  }
 
  value(options?: FieldValueOptions): Date {
    return this.internalValue.toDate();
  }
 
  isEqual(other: FieldValue): boolean {
    return (
      other instanceof TimestampValue &&
      this.internalValue.isEqual(other.internalValue)
    );
  }
 
  compareTo(other: FieldValue): number {
    if (other instanceof TimestampValue) {
      return this.internalValue.compareTo(other.internalValue);
    } else if (other instanceof ServerTimestampValue) {
      // Concrete timestamps come before server timestamps.
      return -1;
    } else {
      return this.defaultCompareTo(other);
    }
  }
}
 
/**
 * Represents a locally-applied ServerTimestamp.
 *
 * Notes:
 * - ServerTimestampValue instances are created as the result of applying a
 *   TransformMutation (see TransformMutation.applyTo()). They can only exist in
 *   the local view of a document. Therefore they do not need to be parsed or
 *   serialized.
 * - When evaluated locally (e.g. for snapshot.data()), they by default
 *   evaluate to `null`. This behavior can be configured by passing custom
 *   FieldValueOptions to value().
 * - With respect to other ServerTimestampValues, they sort by their
 *   localWriteTime.
 */
export class ServerTimestampValue extends FieldValue {
  typeOrder = TypeOrder.TimestampValue;
 
  constructor(
    readonly localWriteTime: Timestamp,
    readonly previousValue: FieldValue | null
  ) {
    super();
  }
 
  value(options?: FieldValueOptions): FieldType {
    if (
      options &&
      options.serverTimestampBehavior === ServerTimestampBehavior.Estimate
    ) {
      return this.localWriteTime.toDate();
    } else if (
      options &&
      options.serverTimestampBehavior === ServerTimestampBehavior.Previous
    ) {
      return this.previousValue ? this.previousValue.value(options) : null;
    } else {
      return null;
    }
  }
 
  isEqual(other: FieldValue): boolean {
    return (
      other instanceof ServerTimestampValue &&
      this.localWriteTime.isEqual(other.localWriteTime)
    );
  }
 
  compareTo(other: FieldValue): number {
    if (other instanceof ServerTimestampValue) {
      return this.localWriteTime.compareTo(other.localWriteTime);
    } else if (other instanceof TimestampValue) {
      // Server timestamps come after all concrete timestamps.
      return 1;
    } else {
      return this.defaultCompareTo(other);
    }
  }
 
  toString(): string {
    return '<ServerTimestamp localTime=' + this.localWriteTime.toString() + '>';
  }
}
 
export class BlobValue extends FieldValue {
  typeOrder = TypeOrder.BlobValue;
 
  constructor(readonly internalValue: Blob) {
    super();
  }
 
  value(options?: FieldValueOptions): Blob {
    return this.internalValue;
  }
 
  isEqual(other: FieldValue): boolean {
    return (
      other instanceof BlobValue &&
      this.internalValue.isEqual(other.internalValue)
    );
  }
 
  compareTo(other: FieldValue): number {
    if (other instanceof BlobValue) {
      return this.internalValue._compareTo(other.internalValue);
    }
    return this.defaultCompareTo(other);
  }
}
 
export class RefValue extends FieldValue {
  typeOrder = TypeOrder.RefValue;
 
  constructor(readonly databaseId: DatabaseId, readonly key: DocumentKey) {
    super();
  }
 
  value(options?: FieldValueOptions): DocumentKey {
    return this.key;
  }
 
  isEqual(other: FieldValue): boolean {
    if (other instanceof RefValue) {
      return (
        this.key.isEqual(other.key) && this.databaseId.isEqual(other.databaseId)
      );
    } else {
      return false;
    }
  }
 
  compareTo(other: FieldValue): number {
    if (other instanceof RefValue) {
      const cmp = this.databaseId.compareTo(other.databaseId);
      return cmp !== 0 ? cmp : DocumentKey.comparator(this.key, other.key);
    }
    return this.defaultCompareTo(other);
  }
}
 
export class GeoPointValue extends FieldValue {
  typeOrder = TypeOrder.GeoPointValue;
 
  constructor(readonly internalValue: GeoPoint) {
    super();
  }
 
  value(options?: FieldValueOptions): GeoPoint {
    return this.internalValue;
  }
 
  isEqual(other: FieldValue): boolean {
    return (
      other instanceof GeoPointValue &&
      this.internalValue.isEqual(other.internalValue)
    );
  }
 
  compareTo(other: FieldValue): number {
    if (other instanceof GeoPointValue) {
      return this.internalValue._compareTo(other.internalValue);
    }
    return this.defaultCompareTo(other);
  }
}
 
export class ObjectValue extends FieldValue {
  typeOrder = TypeOrder.ObjectValue;
 
  constructor(readonly internalValue: SortedMap<string, FieldValue>) {
    super();
  }
 
  value(options?: FieldValueOptions): JsonObject<FieldType> {
    const result: JsonObject<FieldType> = {};
    this.internalValue.inorderTraversal((key, val) => {
      result[key] = val.value(options);
    });
    return result;
  }
 
  forEach(action: (key: string, value: FieldValue) => void): void {
    this.internalValue.inorderTraversal(action);
  }
 
  isEqual(other: FieldValue): boolean {
    if (other instanceof ObjectValue) {
      const it1 = this.internalValue.getIterator();
      const it2 = other.internalValue.getIterator();
      while (it1.hasNext() && it2.hasNext()) {
        const next1: { key: string; value: FieldValue } = it1.getNext();
        const next2: { key: string; value: FieldValue } = it2.getNext();
        if (next1.key !== next2.key || !next1.value.isEqual(next2.value)) {
          return false;
        }
      }
 
      return !it1.hasNext() && !it2.hasNext();
    }
 
    return false;
  }
 
  compareTo(other: FieldValue): number {
    if (other instanceof ObjectValue) {
      const it1 = this.internalValue.getIterator();
      const it2 = other.internalValue.getIterator();
      while (it1.hasNext() && it2.hasNext()) {
        const next1: { key: string; value: FieldValue } = it1.getNext();
        const next2: { key: string; value: FieldValue } = it2.getNext();
        const cmp =
          primitiveComparator(next1.key, next2.key) ||
          next1.value.compareTo(next2.value);
        if (cmp) {
          return cmp;
        }
      }
 
      // Only equal if both iterators are exhausted
      return primitiveComparator(it1.hasNext(), it2.hasNext());
    } else {
      return this.defaultCompareTo(other);
    }
  }
 
  set(path: FieldPath, to: FieldValue): ObjectValue {
    assert(!path.isEmpty(), 'Cannot set field for empty path on ObjectValue');
    if (path.length === 1) {
      return this.setChild(path.firstSegment(), to);
    } else {
      let child = this.child(path.firstSegment());
      if (!(child instanceof ObjectValue)) {
        child = ObjectValue.EMPTY;
      }
      const newChild = (child as ObjectValue).set(path.popFirst(), to);
      return this.setChild(path.firstSegment(), newChild);
    }
  }
 
  delete(path: FieldPath): ObjectValue {
    assert(
      !path.isEmpty(),
      'Cannot delete field for empty path on ObjectValue'
    );
    if (path.length === 1) {
      return new ObjectValue(this.internalValue.remove(path.firstSegment()));
    } else {
      // nested field
      const child = this.child(path.firstSegment());
      if (child instanceof ObjectValue) {
        const newChild = child.delete(path.popFirst());
        return new ObjectValue(
          this.internalValue.insert(path.firstSegment(), newChild)
        );
      } else {
        // Don't actually change a primitive value to an object for a delete
        return this;
      }
    }
  }
 
  contains(path: FieldPath): boolean {
    return this.field(path) !== undefined;
  }
 
  field(path: FieldPath): FieldValue | undefined {
    assert(!path.isEmpty(), "Can't get field of empty path");
    let field: FieldValue | undefined = this;
    path.forEach((pathSegment: string) => {
      if (field instanceof ObjectValue) {
        field = field.internalValue.get(pathSegment) || undefined;
      } else {
        field = undefined;
      }
    });
    return field;
  }
 
  toString(): string {
    return JSON.stringify(this.value());
  }
 
  private child(childName: string): FieldValue | undefined {
    return this.internalValue.get(childName) || undefined;
  }
 
  private setChild(childName: string, value: FieldValue): ObjectValue {
    return new ObjectValue(this.internalValue.insert(childName, value));
  }
 
  static EMPTY = new ObjectValue(
    new SortedMap<string, FieldValue>(primitiveComparator)
  );
}
 
export class ArrayValue extends FieldValue {
  typeOrder = TypeOrder.ArrayValue;
 
  constructor(readonly internalValue: FieldValue[]) {
    super();
  }
 
  value(options?: FieldValueOptions): FieldType[] {
    return this.internalValue.map(v => v.value(options));
  }
 
  forEach(action: (value: FieldValue) => void): void {
    this.internalValue.forEach(action);
  }
 
  isEqual(other: FieldValue): boolean {
    if (other instanceof ArrayValue) {
      if (this.internalValue.length !== other.internalValue.length) {
        return false;
      }
 
      for (let i = 0; i < this.internalValue.length; i++) {
        Iif (!this.internalValue[i].isEqual(other.internalValue[i])) {
          return false;
        }
      }
 
      return true;
    }
 
    return false;
  }
 
  compareTo(other: FieldValue): number {
    if (other instanceof ArrayValue) {
      const minLength = Math.min(
        this.internalValue.length,
        other.internalValue.length
      );
 
      for (let i = 0; i < minLength; i++) {
        const cmp = this.internalValue[i].compareTo(other.internalValue[i]);
 
        if (cmp) {
          return cmp;
        }
      }
 
      return primitiveComparator(
        this.internalValue.length,
        other.internalValue.length
      );
    } else {
      return this.defaultCompareTo(other);
    }
  }
 
  toString(): string {
    return JSON.stringify(this.value());
  }
}